package com.appspot.didit.client.user;

import com.appspot.didit.client.BaseView;
import com.appspot.didit.client.util.Util;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.inject.Inject;

public class RegisterPresenterImpl implements RegisterPresenter {
	private final UserServiceAsync userService = GWT.create(UserService.class);
	private final View view;
	
	@Inject
    public RegisterPresenterImpl(final HandlerManager eventBus, final View view) {

            this.view = view;

            view.getRegisterClickHandlers().addClickHandler(new ClickHandler() {
				public void onClick(ClickEvent event) {
					register(eventBus);
				}
            });
            view.getKeyPressHandler().addKeyPressHandler(new KeyPressHandler() {
				@Override
				public void onKeyPress(KeyPressEvent event) {
					 if (event.getCharCode() == KeyCodes.KEY_ENTER) {
						 register(eventBus);
					 }
				}
            });
            view.getRegisterResetClickHandlers().addClickHandler(new ClickHandler() {
				public void onClick(ClickEvent event) {
					getView().reset();
				}
            });
            
            view.getCheckAvailableClickHandlers().addClickHandler(new ClickHandler() {
				@SuppressWarnings("unchecked")
				public void onClick(ClickEvent event) {		
					String username = view.getUsername().getValue().toString();
					if(!validate(username, "       ", "       ")) {
						view.getRegisterHint().setText("Sie haben den gew\u00fcnschten Benutzernamen eingegeben!");  
					} else {
						view.getWidget().getParent().getParent().setVisible(false);
						RootPanel.get("loading").setVisible(true);
						userService.isAvailable(username, new AsyncCallback() {
			                public void onFailure(Throwable caught) {
			                	view.getWidget().getParent().getParent().setVisible(true);
								RootPanel.get("loading").setVisible(false);
			                    GWT.log("Failed to check the Validity of Username, Exception thrown", caught);
			                }

			                public void onSuccess(Object result) {
			                	view.getWidget().getParent().getParent().setVisible(true);
								RootPanel.get("loading").setVisible(false);
			                    Boolean r = (Boolean)result; 
			                    if (r.booleanValue()) {
			                    	view.getRegisterHint().setText("Der gew\u00fcnschter Benutzername ist noch verf\u00fcgbar!");
			                    } else {
			                    	view.getRegisterHint().setText("Der gew\u00fcnschter Benutzername ist nicht mehr verf\u00fcgbar!"); 
			                        GWT.log("Failed to check the Validity of Username", null);
			                    }
			                }
			            });
					}
				}
            });

    }

    private boolean validate(String username, String password, String passwordRe) {
    	if(username == null || password == null || passwordRe == null) {
    		return false;
    	}
    	
    	if(username.equals("") || password.equals("")) {
    		return false;
    	}
    	
    	if(!password.equals(passwordRe)) {
    		return false;
    	}
    	if(password.length() < 6) {
    		return false;
    	}
    	return true;
    }
    
    public View showRegister() {
            return view;
    }

    public BaseView getView() {
            return view;
    }
    
    public void register(final HandlerManager eventBus) {
    	final String username = view.getUsername().getValue().toString();
		final String password = view.getPassword().getValue().toString();
		final String passwordRe = view.getPasswordRe().getValue().toString();
		view.getWidget().getParent().getParent().setVisible(false);
		RootPanel.get("loading").setVisible(true);
		if(validate(username, password, passwordRe)) {
			userService.newUser(username, Util.encrypt(username, password), new AsyncCallback() {
                public void onFailure(Throwable caught) {
                	RootPanel.get("loading").setVisible(false);
                	view.getWidget().getParent().getParent().setVisible(true);
                	view.getRegisterHint().setText("Fehler auftritt, bitte versuchen Sie noch mal!"); 
                    GWT.log("Failed to register a new account, Exception thrown", caught);
                }
                public void onSuccess(Object result) {
                	User u = (User)result;
                    if (u != null && u.getId() != null) {
                    	UserManager um = UserManager.getInstance();
						um.setUser(u);
                    	eventBus.fireEvent(new LoginSuccessEvent());
                    } else {
                    	view.getWidget().getParent().getParent().setVisible(true);
                    	view.getRegisterHint().setText("Der gew\u00fcnschter Benutzername ist nicht mehr verf\u00fcgbar!"); 
                        GWT.log("Failed to register a new account", null);
                    }
                    RootPanel.get("loading").setVisible(false);
                }
            });
		} else {
			view.getRegisterHint().setText("Ihre Angaben sind nicht komplett");
			view.getWidget().getParent().getParent().setVisible(true);
			RootPanel.get("loading").setVisible(false);
		}
    }

}